// controller 里面导入 model ，调用model 的方法，查询数据库
import Error from '../modles/errorModelSchema';
import logger from '../logger';
import url from 'url';

interface ErrorsType {
  saveErrors: Function;
  getErrorList: Function;
  getErrorByPage: Function;
}
const ErrorsCtrl = <ErrorsType>{};

// 保存error
ErrorsCtrl.saveErrors = (req: any, res: any, next: Function) => {
  const queryData = url.parse(req.url, true)?.query || {};
  let { error }: any = queryData;
  error = JSON.parse(error);
  Error.create({ error: error.errorData }).then((trace) => {
    res.send({
      success: true,
    });
  });
};

// 获取errorlist 列表
ErrorsCtrl.getErrorList = (req: any, res: any, next: Function) => {
  Error.find().then((list) => {
    res.send({
      success: true,
      list,
    });
  });
};

// 分页获取数据
ErrorsCtrl.getErrorByPage = async (req: any, res: any, next: Function) => {
  const { pageIndex, pageSize, searchId, serachIdtype, time } = req.body;
  let dataNumber = (parseInt(pageIndex) - 1) * parseInt(pageSize);
  let total = 0;
  let params: any = {};
  // cid uid ...
  if (serachIdtype === 'cid' && searchId) {
    params = {
      'error.browserid': searchId,
    };
  } else if (serachIdtype === 'uid' && searchId) {
    params = {
      'error.userid': searchId,
    };
  }
  if (time) {
    params['error.time'] = {
      $gt: time[0],
      $lt: time[1],
    };
  }
  // 查询 error 对象下 browserid 字段
  total = await Error.find(params).count();
  Error.find(params)
    .skip(dataNumber)
    .limit(pageSize)
    .then((list) => {
      res.send({
        success: true,
        list,
        total,
      });
    });
};
export default ErrorsCtrl;
